package com.itcoon.cloud.framework.mybatis.config;


import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.itcoon.cloud.framework.mybatis.injector.BaseSqlInjector;
import com.itcoon.cloud.framework.mybatis.interseptor.SqlLogInterceptor;
import com.itcoon.cloud.framework.mybatis.metahandler.BaseMetaObjectHandler;
import com.itcoon.cloud.framework.mybatis.register.InnerInterceptorRegister;
import com.itcoon.cloud.framework.mybatis.metahandler.AbstractMetaObjectHandler;
import com.itcoon.cloud.framework.mybatis.metahandler.DelegateMetaObjectHandler;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import java.util.List;

@AutoConfiguration
public class MybatisPlusAutoConfiguration {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(List<MyBatisPlusConfigurer> configurers) {
        InnerInterceptorRegister register = new InnerInterceptorRegister();
        for (MyBatisPlusConfigurer configurer : configurers) {
            configurer.registerInterceptor(register);
        }
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        List<InnerInterceptor> interceptors = register.getInterceptors();
        for (InnerInterceptor innerInterceptor : interceptors) {
            interceptor.addInnerInterceptor(innerInterceptor);
        }
        return interceptor;
    }


    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return configuration -> {
            configuration.addInterceptor(new SqlLogInterceptor());
        };
    }

    @Bean
    public BaseMetaObjectHandler baseMetaObjectHandler(){
        return new BaseMetaObjectHandler();
    }

    @Bean
    @Primary
    public DelegateMetaObjectHandler delegateMetaObjectHandler(List<AbstractMetaObjectHandler> metaObjectHandlers){
        return new DelegateMetaObjectHandler(metaObjectHandlers);
    }

    @Bean
    @Primary
    public BaseSqlInjector baseSqlInjector(){
        return new BaseSqlInjector();
    }
}
